<?php

/**
 * ClassName:关注用户处理器
 * @auditor LeiJunXiang
 * @time 2024/11/25
 */

namespace app\tool\user;

use app\factory\Factory;
use app\modelOpreate\user\ForumUserOpe;
use app\tool\ToolBase;
use think\facade\Db;

class AttentionUserHandler extends ToolBase
{
    const TOOL_ATTENTION_USER_HANDLER = 'AttentionUserHandler';
    /**
     * (true/false)开始处理(用户id,被关注的用户id)
     */
    public function startHandler($userId, $attentionUserId)
    {
        if ($userId && $attentionUserId) {
            try {
                // 开始事务
                Db::startTrans();

                // 增加关注粉丝和关注数
                $this->addAttentionAndNumber($userId, $attentionUserId);

                // (关注用户id,用户id)
                $this->addFanAndNumber($attentionUserId,$userId);

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->errMsg = "关注失败，请重试!(3)";
                $this->errCode = FAIL;
            }
        } else {
            $this->errMsg = "数据不完整，请重试!";
            $this->errCode = FAIL;
        }
        return $this->isGoOn();
    }

    /**
     * 增加关注粉丝和关注数
     */
    protected function addAttentionAndNumber($userId, $attentionUserId)
    {
        $tool = Factory::getInstance()->getToolObj(ForumUserOpe::TOOL_FORUM_USER_OPE);
        //增加关注用户id(用户id,关注用户id)
        $flag = $tool->addAttentionUserId($userId, $attentionUserId);
        //新增关注数
        $tool->addAttentionNumber($userId);
        if (!$flag) {
            $this->errMsg = "关注失败，请重试!";
            $this->errCode = FAIL;
        }
    }

    /**
     * 增加粉丝和粉丝数(关注用户id,用户id)
     */
    protected function addFanAndNumber($attentionUserId,$userId)
    {
        if (!$this->isGoOn()) {
            return;
        }
        $tool = Factory::getInstance()->getToolObj(ForumUserOpe::TOOL_FORUM_USER_OPE);
        //增加粉丝用户id(用户id,粉丝用户id)
        $flag = $tool->addFanUserId($userId, $attentionUserId);
        //新增粉丝数
        $tool->addFanNumber($attentionUserId);
        if (!$flag) {
            $this->errMsg = "关注失败，请重试!(1)";
            $this->errCode = FAIL;
        }
    }


}